package com.app.system.permission.web.permission;

import com.app.log.annotation.MyLog;
import com.app.system.permission.en.ResourceType;
import com.app.system.permission.model.SysPermission;
import com.app.system.permission.model.SysRole;
import com.app.system.permission.service.ShiroService;
import com.app.system.permission.service.SysPermissionService;
import com.app.system.permission.service.SysRoleService;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.exception.AjaxException;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Created by wcf-pc on 2018/5/24.
 */
@Controller
@SuppressWarnings("all")
@RequestMapping("/permission/sysPermission/*")
public class SysPermissionController {

    @Resource
    private SysPermissionService sysPermissionService;
    @Resource
    private ShiroService shiroService;
    @Resource
    private SysRoleService sysRoleService;

    @RequestMapping("list")
    @RequiresPermissions("sysPermission:list")
    public void list() {

    }

    @RequestMapping("loadTreeData")
    @ResponseBody
    @RequiresPermissions("sysPermission:loadTreeData")
    public Map loadTreeData() {

        List<Map> childrenList = this.sysPermissionService.mapTreeData();
        Map map = Maps.newLinkedHashMap();
        map.put("id", null);
        map.put("name", "根目录");
        map.put("open", true);
        map.put("children", childrenList);

        return map;
    }

    @RequestMapping("loadButtonData")
    @ResponseBody
    @RequiresPermissions("sysPermission:loadButtonData")
    public Map loadButtonData(HttpServletRequest request) {
        int parentId = ParamUtils.getInt(request, "parentId", 0);
        List<SysPermission> dataDictList = this.sysPermissionService.findListByParentId(parentId);
        List<Map> listData = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(dataDictList)) {
            for (SysPermission sysPermission : dataDictList) {
                Map<String, Object> item = Maps.newHashMap();

                item.put("parentId", sysPermission.getSysPermission() == null ? 0 : sysPermission.getSysPermission().getId());
                item.put("id", sysPermission.getId());
                item.put("name", sysPermission.getName());
                item.put("permission", sysPermission.getPermission());
                item.put("url", sysPermission.getUrl());
                item.put("enabled", sysPermission.getEnabled());
                item.put("sortIndex", sysPermission.getSortIndex());
                item.put("memo", sysPermission.getMemo());
                listData.add(item);
            }
        }
        return LayUiUtils.list(listData);
    }

    @MyLog(value = "权限功能删除")
    @RequestMapping("deleteButtonData")
    @ResponseBody
    @RequiresPermissions("sysPermission:deleteButtonData")
    public Response deleteDataDict(HttpServletRequest request) {
        String idsString = ParamUtils.getString(request, "ids", "");
        if (!Strings.isNullOrEmpty(idsString)) {
            String[] ids = idsString.split(",");
            String result = this.sysPermissionService.deleteByIds(ids);
            if ("ok".equals(result)) {
                return new Response("0001", "删除成功");
            }
        }
        return new Response("0002", "删除失败");
    }


    @RequestMapping("formButton")
    @RequiresPermissions("sysPermission:formButton")//此处不配置，则此方法将不经过权限验证
    public void formButton(HttpServletRequest request, ModelMap modelMap) throws Exception {
        int parentId = ParamUtils.getInt(request, "parentId", 0);
        int id = ParamUtils.getInt(request, "id", 0);
        SysPermission parent = this.sysPermissionService.findOne(parentId);
        Precondition.checkSqdsArguement(parent != null, "无效操作");

        SysPermission sysPermission = this.sysPermissionService.findOne(id);
        if (sysPermission == null) {
            sysPermission = new SysPermission();
            sysPermission.setEnabled(0);
            sysPermission.setMenuType(1);
            sysPermission.setSysPermission(parent);
        }
        if(sysPermission.getMenuType() == null){
            sysPermission.setMenuType(1);
        }
        modelMap.addAttribute("sysPermission", sysPermission);

        List<SysRole> userRoleList = sysPermission.getRoles();
        List<Integer> roleIds = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(userRoleList)) {
            for (SysRole sysRole : userRoleList) {
                roleIds.add(sysRole.getId());
            }
        }
        modelMap.addAttribute("roleIds", roleIds);

        List<SysRole> sysRoleList = this.sysRoleService.findAll();
        modelMap.addAttribute("sysRoleList", sysRoleList);
    }

    @MyLog(value = "权限功能保存")
    @RequestMapping("saveButton")
    @ResponseBody
    @RequiresPermissions("sysPermission:saveButton")
    public Response saveButton(HttpServletRequest request) throws AjaxException {
        Integer id = ParamUtils.getInt(request, "id", 0);
        int parentId = ParamUtils.getInt(request, "parentId", 0);
        SysPermission parent = this.sysPermissionService.findOne(parentId);
        if (parent == null) {
            throw new AjaxException("002", "请选择功能对应的菜单");
        }

        SysPermission item = this.sysPermissionService.findOne(id);
        if (item == null) {
            item = new SysPermission();
            item.setSysPermission(parent);
            item.setResourceType(ResourceType.button.toString());
        }
        ServletRequestDataBinder binder = new ServletRequestDataBinder(item);
        binder.bind(request);

        int[] roles = ParamUtils.getIntParameters(request, "role");
        List<SysRole> sysRoleList = Lists.newArrayList();
        if (roles != null && roles.length > 0) {
            for (int r : roles) {
                SysRole sysRole = new SysRole();
                sysRole.setId(r);
                sysRoleList.add(sysRole);
            }
        }
        item.setRoles(sysRoleList);

        this.sysPermissionService.save(item);

        return new Response("0001", "保存成功");
    }

    @MyLog(value = "权限功能保存")
    @RequestMapping("saveCellEditButton")
    @ResponseBody
    @RequiresPermissions("sysPermission:saveCellEditButton")
    public Response saveCellEditButton(HttpServletRequest request) throws AjaxException {
        Integer id = ParamUtils.getInt(request, "id", 0);
        int parentId = ParamUtils.getInt(request, "parentId", 0);
        SysPermission parent = this.sysPermissionService.findOne(parentId);
        if (parent == null) {
            throw new AjaxException("002", "请选择功能对应的菜单");
        }

        SysPermission item = this.sysPermissionService.findOne(id);
        if (item == null) {
            item = new SysPermission();
            item.setSysPermission(parent);
            item.setResourceType(ResourceType.button.toString());
        }
        ServletRequestDataBinder binder = new ServletRequestDataBinder(item);
        binder.bind(request);

        this.sysPermissionService.save(item);

        return new Response("0001", "保存成功");
    }

    @RequestMapping("formMenu")
    @RequiresPermissions("sysPermission:formMenu")
    public void formMenu(HttpServletRequest request, ModelMap modelMap) throws Exception {
        int parentId = ParamUtils.getInt(request, "parentId", 0);
        int id = ParamUtils.getInt(request, "id", 0);
        SysPermission parent = this.sysPermissionService.findOne(parentId);

        SysPermission sysPermission = this.sysPermissionService.findOne(id);
        if (sysPermission == null) {
            sysPermission = new SysPermission();
            sysPermission.setEnabled(0);
            sysPermission.setMenuType(1);
            if (parent != null) {
                sysPermission.setSysPermission(parent);
            }
        }
        if(sysPermission.getMenuType() == null){
            sysPermission.setMenuType(1);
        }
        modelMap.addAttribute("sysPermission", sysPermission);

        List<SysRole> userRoleList = sysPermission.getRoles();
        List<Integer> roleIds = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(userRoleList)) {
            for (SysRole sysRole : userRoleList) {
                roleIds.add(sysRole.getId());
            }
        }
        modelMap.addAttribute("roleIds", roleIds);

        List<SysRole> sysRoleList = this.sysRoleService.findAll();
        modelMap.addAttribute("sysRoleList", sysRoleList);
    }

    @MyLog(value = "权限菜单保存")
    @RequestMapping("saveMenu")
    @ResponseBody
    @RequiresPermissions("sysPermission:saveMenu")
    public Response saveMenu(HttpServletRequest request) throws AjaxException {
        Integer id = ParamUtils.getInt(request, "id", 0);
        int parentId = ParamUtils.getInt(request, "parentId", 0);

        SysPermission parent = this.sysPermissionService.findOne(parentId);
        SysPermission item = this.sysPermissionService.findOne(id);

        if (item == null) {
            item = new SysPermission();
            item.setResourceType(ResourceType.menu.toString());
            if (parent != null) {
                item.setSysPermission(parent);
            }
        }

        ServletRequestDataBinder binder = new ServletRequestDataBinder(item);
        binder.bind(request);

        int[] roles = ParamUtils.getIntParameters(request, "role");
        List<SysRole> sysRoleList = Lists.newArrayList();
        if (roles != null && roles.length > 0) {
            for (int r : roles) {
                SysRole sysRole = new SysRole();
                sysRole.setId(r);
                sysRoleList.add(sysRole);
            }
        }
        item.setRoles(sysRoleList);

        this.sysPermissionService.save(item);

        return new Response("0001", "保存成功");
    }

    @MyLog(value = "权限是否启用设置")
    @RequestMapping("setEnabled")
    @ResponseBody
    @RequiresPermissions("sysPermission:setEnabled")//此处不配置，则此方法将不经过权限验证
    public Response setEnabled(HttpServletRequest request) {
        Integer id = ParamUtils.getInt(request, "id", 0);
        Integer enabled = ParamUtils.getInt(request, "enabled", 0);
        SysPermission sysPermission = this.sysPermissionService.findOne(id);
        if (sysPermission == null || !(enabled == 0 || enabled == 1)) {
            throw new AjaxException("002", "无效操作");
        }
        sysPermission.setEnabled(enabled);
        this.sysPermissionService.save(sysPermission);
        return new Response("0001", "更新成功");
    }

    @MyLog(value = "权限菜单删除")
    @RequestMapping("deleteMenuData")
    @ResponseBody
    @RequiresPermissions("sysPermission:deleteMenuData")
    public Response deleteMenuData(HttpServletRequest request) {
        try {
            int id = ParamUtils.getInt(request, "id", 0);
            String result = this.sysPermissionService.deleteById(id);
            if ("ok".equals(result)) {
                return new Response("0001", "删除成功");
            }
        } catch (Exception e) {

        }
        return new Response("0002", "删除失败，请将子项删除");
    }

    /**
     * 动态更新shiro缓存权限
     */
    @MyLog(value = "更新shiro缓存权限")
    @RequestMapping("clearShiroCatch")
    @ResponseBody
    @RequiresPermissions("sysPermission:clearShiroCatch")
    public Response clearShiroCatch() {
        this.shiroService.clearShiroCatch();
        return new Response("0001", "更新成功，最新权限已生效");
    }
}
